import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/welcome',
    name: 'Welcome',
    redirect: '/user-list',
    component: () => import('../views/Welcome.vue'),
    children: [
      {
        path: '/user-list',
        name: 'userlist',
        component: () => import('../views/users/userList.vue')
      },
      {
        path: '/role-list',
        name: 'role-list',
        component: () => import('../views/roleList/roleList.vue')
      },
      {
        path: '/permission-list',
        name: 'permission-list',
        component: () => import('../views/roleList/permissionList.vue')
      },
      {
        path: '/shopping-list',
        name: 'shoppingList',
        component: () => import('../views/shopping/shoppingList.vue')
      },
      {
        path: '/shopping-classify',
        name: 'shoppingClassify',
        component: () => import('../views/shopping/shoppingClassify.vue')
      },
      {
        path: '/classify-list',
        name: 'classifyList',
        component: () => import('../views/shopping/classifyList.vue')
      },
      {
        path: '/order-list',
        name: 'orderList',
        component: () => import('../views/order/orderList.vue')
      },
      {
        path: '/data-list',
        name: 'dataList',
        component: () => import('../views/dataList/dataList.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // console.log('from:', from.meta, 'to:', to)
  if (to.path === '/login') {
    window.sessionStorage.clear()
    return next()
  }
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
